package com.sunwayworld.basemodule.coredata.product.service.impl;

import com.sunwayworld.basemodule.coredata.product.bean.LimsProductBean;
import com.sunwayworld.basemodule.coredata.product.bean.LimsProductMainBean;
import com.sunwayworld.basemodule.coredata.product.dao.LimsProductMainDao;
import com.sunwayworld.basemodule.coredata.product.service.LimsProductMainService;
import com.sunwayworld.basemodule.coredata.product.service.LimsProductService;
import com.sunwayworld.framework.at.annotation.AuditTrailEntry;
import com.sunwayworld.framework.at.annotation.AuditTrailType;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.utils.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Repository
@GikamBean
public class LimsProductMainServiceImpl implements LimsProductMainService {

    @Autowired
    private LimsProductMainDao limsProductMainDao;

    @Autowired
    private LimsProductService productService;

    @Override
    @SuppressWarnings("unchecked")
    public LimsProductMainDao getDao() {
        return limsProductMainDao;
    }

    @Override
    @Transactional
    @AuditTrailEntry(AuditTrailType.INSERT)
    public Long insert(RestJsonWrapperBean jsonWrapper) {
        LimsProductMainBean limsProductMain = jsonWrapper.parseUnique(LimsProductMainBean.class);
        limsProductMain.setId(ApplicationContextHelper.getNextIdentity());
        getDao().insert(limsProductMain);
        return limsProductMain.getId();
    }

    @Override
    @Transactional
    public void delete(RestJsonWrapperBean wrapper) {
        List<LimsProductMainBean> parse = wrapper.parse(LimsProductMainBean.class);
        if(CollectionUtils.isEmpty(parse)) return;
        // 级联删除
        List<LimsProductBean> productBeans = new ArrayList<>();
        parse.forEach(e -> {
            LimsProductBean methodBean = new LimsProductBean();
            methodBean.setProductMainId(e.getId());
            productBeans.add(methodBean);
        });
        productService.getDao().deleteBy(productBeans, "productMainId");
        getDao().deleteBy(parse);
    }
}
